package com.taotao.search.service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.search.pojo.Item;
import com.taotao.search.pojo.SearchResult;
@Repository
public class SearchDaoImpl implements SearchDao {
	@Autowired
	private SolrServer solrServer;
	
	@Override
	public SearchResult getItems(SolrQuery query){
		SearchResult result=new SearchResult();
		List<Item> items=new LinkedList<>();
			try {
				QueryResponse  response = solrServer.query(query);
				SolrDocumentList results = response.getResults();
				result.setCountTotal(results.getNumFound());
				//取高亮显示
				Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
				for (SolrDocument document : results) {
					Item item=new Item();
					item.setId((String)document.get("id"));
					//取高亮显示的结果
					List<String> list = highlighting.get(document.get("id")).get("item_title");
					String title = "";
					if (list != null && list.size()>0) {
						title = list.get(0);
					} else {
						title = (String) document.get("item_title");
					}
					item.setTitle(title);
					item.setItem_des((String)document.get("item_desc"));
					item.setPrice((long)document.get("item_price"));
					item.setSell_point((String)document.get("item_sell_point"));
					item.setImage((String)document.get("item_image"));
					item.setCategory_name((String)document.get("item_category_name"));
					items.add(item);
				}
			} catch (SolrServerException e) {
				e.printStackTrace();
			}
			
		result.setItems(items);
		return result;
	}

}
